package com.olive.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

//登录超时 or 异地登录
public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {
    ObjectMapper objectMapper = new ObjectMapper();
    //session过去，删除（多端登录）
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        //返回json数据
        HashMap<String, String> map = new HashMap<>();
        map.put("code", "404");
        map.put("message", "你的登录已超时或已经在另一台机器登录"+event.getSessionInformation().getLastRequest());
        HttpServletResponse response = event.getResponse();
        String json = objectMapper.writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
